package com.xiong.springsecurity.controller;


import com.xiong.springsecurity.domain.ResponseResult;
import com.xiong.springsecurity.domain.User;
import com.xiong.springsecurity.mapper.UserMapper;
import com.xiong.springsecurity.service.LoginService;
import com.xiong.springsecurity.service.impl.LoginUser;
import com.xiong.springsecurity.utils.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 必须是这个注解，因为是模拟前后端分离的restful风格的请求，要求每个方法返回 json
 * @author XiongDa
 */
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final LoginService loginService;

    private final RedisCache redisCache;

    @PostMapping(value = "/user/login")
    public ResponseResult<Map<String, String>> login(@RequestBody User user){
        return loginService.login(user);
    }

    /**
     * 从退出登入的请求中携带 token, 所以我们可以从 SecurityContextHolder 中获取到我们在自定义过滤器时存入的用户信息
     * 拿到用户id , 删除这个用户的 redis 信息
     * @date: 2023/6/14 16:43
     */
    @GetMapping(value = "/user/logout")
    public ResponseResult<Object> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult<Object>(200,"退出成功");
    }

}
